import React, { PureComponent } from 'react';
import { Table, Select, Modal, Radio, Input, message,Icon } from 'antd';
import api from '../../../../../../api/api';
const Option = Select.Option;
const RadioGroup = Radio.Group;
const confirm = Modal.confirm;
const YEARITEM =setSelect()
function setSelect(){
  const years = new Date().getFullYear();
  let yearOld = []
  for (let i = 0; i <= 100; i++) {
    yearOld.push((years - i).toString())
  }
  return yearOld
}
let timeout;
export default class ChoseSlowSickTabless extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      columns: [],
      data: [{
        diseaseDate: '',
        diseaseId: ''
      }],
      optionsData: [],
      saveOptionsData:[],
      visible: false,
      getSickYear: '2012',
      sickIndex: 0,
      ownSickListData: [],
      value: '',
      loading: false,
      searchLoading:false
    }
  }
  componentDidMount() {
    this.getDiseasesList()
  }

  getDiseasesList = async () => {
    this.initColumns()
  }
  initColumns = async () => {
    this.setState({
      loading: true,
      value:undefined
    })
    const self = this
    let sickData = this.props.dataMain || this.state.data;
    // 判断是否有空的
    // let sickData = data.chronicDiseases;
    if (sickData.length<1 || !sickData.some(item => !item.id)) {
      const newData = {
        diseaseDate: '',
        diseaseId: ''
      }
      sickData.push(newData)
    }
    this.setState({
      data:sickData,
      columns: [{
        title: '疾病',
        dataIndex: 'name',
        key: 'name',
        render: (text, record, index) => {
          const optionData = this.state.optionsData || this.state.saveOptionsData
          let options = optionData.map(d => <Option key={d.id}>{d.name} {d.icd10}</Option>);
          if (optionData.length < 1) {
            options = <Option key='没有相关数据' disabled>没有相关数据</Option>;
          }
          if (this.state.searchLoading) {
            options = <Option key='搜索中' disabled><Icon type="loading" /> 搜索中</Option>;
          }
          return (<div className="cursor">
            {record.diseaseName ? <div>{record.diseaseName}({ record.icd10 })</div>:<Select
              mode="combobox"
              value={record.diseaseId}
              placeholder='请搜索'
              notFoundContent=""
              defaultActiveFirstOption={false}
              showArrow={false}
              filterOption={false}
              onChange={(value) => self.sickChange(value, index)}
              onSelect={(value, options) => this.onSelectFun(value, options, index)}
              onBlur={ ()=>this.isCheckValue()}
              style={{minWidth:'220px'}}
            >
              {options}
            </Select>}
          </div>)
        },
      }, {
        title: '确诊年份',
        dataIndex: 'year',
        key: 'year',
        render: (text, record, index) => {
          let dateVal = record.diseaseDate || ''
          return (
          <div>
            {record.diseaseName && index !== this.state.data.length-1 ?<div>{ record.diseaseDate?record.diseaseDate:undefined }</div>:<div className="cursor" onClick={() => this.choseDataYear(index, record.diseaseDate)}>
                <Input className="width150" placeholder="选择日期" value={dateVal} />
                </div> }
          </div>
          )
        }
      }, {
        title: '操作',
        key: 'action',
        width:100,
        render: (text, record, index) => (
          <div className="tabledisplayNone">
            <span className="cursor" style={{marginRight:'15px',display:'inline-block'}} onClick={ ()=>this.deleteSlowSick(record,index) }>
              删除
            </span>
            {index === this.state.data.length-1?<span onClick={() => this.editOwnSickFun()} className="saveBtn">添加</span>:null}
          </div>
        ),
      }]
    })
    this.setState({
      loading:false
    })
  }
  choseDataYear = (index, year) => {
    const { data } = this.state;
    if (!data[index].diseaseId) {
      message.error('请先选择疾病');
      return false;
    }
    typeof(str)=='string'
    this.setState({
      getSickYear:typeof(year)=='string'?year:year.toString(),
      sickIndex: index,
      visible: true
    })
  }
  sickChange = (value, index) => {
    if (index || index === 0) {
      let newMainData = this.state.data;
      console.log('newMaindata',index, newMainData)
      newMainData[index].diseaseId = value
      this.setState({
        data: newMainData,
        value: value
      })
      this.fetch( value,optdata => this.setState({ optionsData: optdata, data: newMainData }));
    }
    }
  // 搜索慢病
  fetch(value, callback) {
    this.setState({
      searchLoading:true
    })
    const self = this
    if (timeout) {
      clearTimeout(timeout);
      timeout = null;
    }
    // currentValue = value;
    async function fake() {
      const search = await api.getSlowSickList(value,0,50)
      self.setState({
        searchLoading:false
      })
      const { data } = self.state;
      let searchFilter = search.filter(item =>
        !data.some(disease => item.id === disease.diseaseId)
      )
      if (searchFilter.length > 0) {
        self.setState({
          saveOptionsData: searchFilter
        })
      }
      callback(searchFilter);
    }
    timeout = setTimeout(fake, 1000);
  }
  onSelectFun = (value, options, index) => {
    let newMainData = this.state.data;
    console.log(111,value,options,index,this.state.optionsData)
    const self = this;
    const sickData = (this.state.optionsData.filter(item => item.id === value))[0];
    newMainData[index].diseaseId = value
    newMainData[index].diseaseName = sickData.name
    newMainData[index].icd10 = sickData.icd10
    this.setState({
      data: newMainData,
      value:options.props.children
    }, () => {
      this.sickChange(options.props.children)
    })
  }
  isCheckValue = () => {
    const { data } = this.state;
    const [last] = [...data].reverse();
    if (!last.diseaseId) {
      this.setState({
        value:''
      })
    }
  }
  onChange = (value) => {
    this.setState({
      getSickYear:value.target.value
    })
  }
  // 选择年限
  handleOk = () => {
    const { sickIndex, data, getSickYear } = this.state;
    let getData = data;
    getData[sickIndex].diseaseDate = getSickYear
    this.setState({
      data:getData,
      visible:false
    })
  }
  handleCancel = () => {
    this.setState({
      visible:false
    })
  }
  // 选择慢病情况
  editOwnSickFun =async () => {
    const { patientId } = this.props;
    let { data } = this.state;
    const isRequest = data.some(item => !item.diseaseId);
    if (isRequest) {
      message.error(`请录入本条慢病后添加`);
      return false;
    }
    const newData = {
      diseaseDate: '',
      diseaseId: '',
      diseaseName: ''
    }
    data.push(newData)
    this.setState({
      data:[...data]
    })

    // data = data.filter(item => {
    //   return item.diseaseId
    // })
    // data = data.map(item => {
    //   if (!item.date) {
    //     item.date = undefined
    //   }
    //   return item;
    // })
    // updateDiseaseInfo.chronicDiseases = data
    // await api.updateDiseaseInfo(patientId, updateDiseaseInfo);
    // this.initColumns()
  }
  // 删除慢病
  deleteSlowSick = async (value, index) => {
    const self = this
    const { patientId } = this.props;
    let { data } = this.state;
    const deleteData = {
      familyDiseases: [],
      chronicDiseases: [value]
    };
    confirm({
      title: '确认要删除么?',
      async onOk() {
        try {
          await api.removeDiseaseInfo(patientId, deleteData);
          let newData = [...data];
          if (data.length === 1) {
            newData = [{
              diseaseDate: '',
              diseaseId: ''
            }]
          } else {
            newData.splice(index, 1);
          }
          self.setState({
            data:newData
          })
          // self.initColumns()
        } catch (e) {
          message.error(`删除失败 ${e.message}`);
        }
      },
      onCancel() {}
    });
  }
  render() {
    console.log(123,this.props.dataMain)
    return (
      <div>
        <Table loading={this.state.loading} className="sickTable" columns={this.state.columns} dataSource={this.state.data} pagination={false} rowKey='key' />
        <Modal
          title="请选择患病年份"
          className="slowModalW"
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          <RadioGroup className="slowSick" options={YEARITEM} onChange={this.onChange} value={this.state.getSickYear} />
        </Modal>
      </div>
    );
  }
}
